import React, { useEffect, useState } from "react";
import { Checkbox, Select, Form, Button, Input } from "antd";
import InputNumberComponent from "@/components/iteration/InputNumberComponent";
import "@/styles/pages/general-export.scss";
import { exportUser as handleExport, getExportParams } from "@/api/system/user";
import PropTypes from "prop-types";
const CheckboxComponent = ({ options, onChange }) => {
  const [checkedList, setCheckedList] = useState([]);
  const [checkAll, setCheckAll] = useState(false);
  const indeterminate = checkedList.length > 0 && checkedList.length < options.length;

  let optionsObject = null;

  const onhandleChange = (values) => {
    setCheckedList(values);
    setCheckAll(values.length === options.length);

    if (optionsObject === null) {
      let temp = {};
      for (const item of options) {
        temp[item.field] = item;
      }
      optionsObject = temp;
    }

    onChange &&
      onChange(
        values,
        values.map((value) => optionsObject[value])
      );
  };

  const onCheckAllChange = (e) => {
    const values = e.target.checked ? options.map(({ field }) => field) : [];
    onhandleChange(values);
  };

  return (
    <div className="checkbox-card">
      <div style={{ marginBottom: "8px" }}>
        <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
          全选
        </Checkbox>
      </div>
      <Checkbox.Group value={checkedList} onChange={onhandleChange}>
        {options.map((item) => (
          <Checkbox key={item.field} value={item.field}>
            {item.label}
          </Checkbox>
        ))}
      </Checkbox.Group>
    </div>
  );
};
CheckboxComponent.propTypes = {
  options: PropTypes.array.isRequired,
  onChange: PropTypes.func.isRequired,
};

const CheckDataComponent = ({ onChange }) => {
  const [isCustom, setIsCustom] = useState(false);
  const [inputNumber, setInputNumber] = useState("1");
  const [selectValue, setSelectValue] = useState("");

  const options = [
    { value: "", label: "全部" },
    { value: "10", label: "前10条记录" },
    { value: "50", label: "前50条记录" },
    { value: "100", label: "前100条记录" },
    { value: "200", label: "前200条记录" },
    { value: "500", label: "前500条记录" },
    { value: "1000", label: "前1000条记录" },
  ];

  const hanldeResult = (value) => {
    onChange && onChange(value);
  };

  const handleInput = (value) => {
    setInputNumber(value);
    hanldeResult(value);
  };

  const onSelect = (value) => {
    setSelectValue(value);
    hanldeResult(value);
  };

  const typeChange = (e) => {
    setIsCustom(e.target.checked);
    hanldeResult(e.target.checked ? inputNumber : selectValue);
  };

  return (
    <div className="checkData-card">
      {isCustom ? (
        <div className="card-item">
          <InputNumberComponent
            placeholder="请输入"
            addonBefore="前"
            addonAfter="条记录"
            value={inputNumber}
            min={1}
            onChange={(e) => handleInput(e.target.value)}
          />
        </div>
      ) : (
        <div className="card-item">
          <Select value={selectValue} options={options} onChange={onSelect} />
        </div>
      )}
      <div className="card-item" style={{ width: "100px", padding: "0px 8px" }}>
        <Checkbox checked={isCustom} onChange={typeChange}>
          自定义
        </Checkbox>
      </div>
    </div>
  );
};
CheckDataComponent.propTypes = {
  onChange: PropTypes.func.isRequired,
};

const FormComponent = ({ options, onFinish, initialValues }) => {
  const [from] = Form.useForm();

  const handleFinish = (values) => {
    onFinish && onFinish(values);
  };

  return (
    <Form
      className="modal-form-card"
      initialValues={initialValues}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      autoComplete="off"
      form={from}
      onFinish={handleFinish}
    >
      <Form.Item>
        <Button htmlType="submit">导出</Button>
      </Form.Item>
      <Form.Item name="sheetName" label="工作表名称">
        <Input placeholder="请输入工作表名称" />
      </Form.Item>

      <Form.Item name="title" label="标题">
        <Input placeholder="请输入标题" />
      </Form.Item>

      <Form.Item name="count" label="数量选择">
        <CheckDataComponent />
      </Form.Item>

      <Form.Item name="fields" label="字段选择">
        <CheckboxComponent options={options} />
      </Form.Item>
    </Form>
  );
};
FormComponent.propTypes = {
  options: PropTypes.array,
  onFinish: PropTypes.func,
  initialValues: PropTypes.object,
};

const GeneralComponent = () => {
  const [fields, setFields] = useState([]);

  useEffect(() => {
    getExportParams().then((res) => {
      setFields(res);
    });
  }, []);

  const onFinish = async (values) => {
    const res = await handleExport(values);
    const fileName = values.sheetName ? `-${values.sheetName}` : "";
    const url = URL.createObjectURL(res); // 创建一个URL指向该Blob对象
    const link = document.createElement("a");
    link.href = url;
    link.download = `${new Date().getTime() + fileName}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url); // 释放URL对象
  };

  return (
    <div className="export-wrapper">
      <FormComponent options={fields} onFinish={onFinish} />
    </div>
  );
};
export default GeneralComponent;
